package sysmap

import (
	"context"
	"fmt"
	"gitee.com/bobo-rs/creative-framework/pkg/utils"
	"gitee.com/bobo-rs/ecomp-analyzer-services/consts"
	"gitee.com/bobo-rs/ecomp-analyzer-services/framework/dao"
	"gitee.com/bobo-rs/ecomp-analyzer-services/framework/model"
	"gitee.com/bobo-rs/ecomp-analyzer-services/library/exception"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
)

// GetList 获取字典列表数据
func (m *sSysMap) GetList(ctx context.Context, in model.SysMapGetListInput) (out *model.SysMapGetListOutput, err error) {
	out = &model.SysMapGetListOutput{}
	var (
		where   = g.Map{}
		columns = dao.SysMap.Columns()
	)
	// 字典名
	if len(in.Name) > 0 {
		where[columns.Name+consts.OrmWhereLike] = utils.OrmWhereLike(in.Name)
	}
	// 字典类型
	if in.IsDisable > -1 {
		where[columns.IsDisable] = in.IsDisable
	}

	// 获取字典列表
	err = m.MapModel().ListAndTotal(ctx, model.CommonListAndTotalInput{
		CommonPaginationItem: in.CommonPaginationItem,
		Where:                where,
		Sort:                 fmt.Sprintf(`%s %s`, columns.Id, consts.SortDesc),
	}, &out.Rows, &out.Total)
	return
}

// GetDetail 获取字典详情
func (m *sSysMap) GetDetail(ctx context.Context, id uint) (detail *model.SysMapDetailItem, err error) {
	detail = &model.SysMapDetailItem{}
	// 获取详情
	err = m.GetDetailById(ctx, id, &detail)
	if err != nil {
		return nil, exception.New(`暂无数据`)
	}
	return
}

// DeleteSysMap 删除系统字典
func (m *sSysMap) DeleteSysMap(ctx context.Context, id uint) error {
	detail := model.SysMapBasicItem{}
	err := m.GetDetailById(ctx, id, &detail)
	if err != nil {
		return exception.New(`暂无数据`)
	}

	// 删除数据
	return dao.SysMap.Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		err = m.MapModel().DeletePri(ctx, id)
		if err != nil {
			return err
		}
		// 关联字典值
		_ = m.ValueModel().Delete(ctx, g.Map{
			dao.SysMapValue.Columns().Name: detail.Name,
		})
		return nil
	})
}

// Map 通过字典名获取字典值
func (m *sSysMap) Map(ctx context.Context, name string) (map[string]string, error) {
	// 获取所有字典列表
	sysMapAll, err := m.GetMapAll(ctx)
	if err != nil {
		return nil, err
	}

	// 是否存在
	sysMap, ok := sysMapAll[name]
	if !ok {
		return nil, exception.Newf(`字典[%s]对应值不存在`, name)
	}
	return sysMap, nil
}

// MustMap 通过字典名获取字典
func (m *sSysMap) MustMap(ctx context.Context, name string) map[string]string {
	sysMap, err := m.Map(ctx, name)
	if err != nil {
		g.Log().Debug(ctx, `字典不存在`, name, err)
		return nil
	}
	return sysMap
}

// Exists 检测字典是否存在
func (m *sSysMap) Exists(ctx context.Context, name string) bool {
	// 获取字典
	if _, err := m.Map(ctx, name); err != nil {
		return false
	}
	return true
}

// ValExists 字典值检测是否存在
func (m *sSysMap) ValExists(ctx context.Context, name string, value g.Var) (bool, error) {
	// 获取字典
	sysMap, err := m.Map(ctx, name)
	if err != nil {
		return false, err
	}
	// 是否存在
	if _, ok := sysMap[value.String()]; !ok {
		return false, exception.Newf(`字典值[%s]不存在`, value.String())
	}
	return true, nil
}
